<template>
    <div class="common-layout">
        <el-container >
            <el-aside  width="25%"  >
                <vxe-table height="800"
                    border ref="listGrid"
                    size="mini" :row-config="{isCurrent: true, isHover: true}"
                           @currentChange="handleSelectionChange"
                    :data="lkViewList">
                <vxe-column type="seq" width="60"></vxe-column>
                <vxe-column field="viewDispName" title="视图名"></vxe-column>
            </vxe-table>
            </el-aside>
            <el-container>
                <el-header>
                    <el-button size="default" type="primary" @click="handleAdd">新建</el-button>
                    <el-button size="default" type="success" :disabled="single" @click="handleUpdate">修改</el-button>
                    <el-button size="default" type="danger" :disabled="multiple" @click="handleDelete">删除</el-button>
                </el-header>
                <el-main >
                    <div style="padding: 0px 15px">
                        <vxe-form :data="form" size="mini">
                            <vxe-form-item field="viewDispName" title="视图别名" :span="12" :item-render="{name:'input'}"></vxe-form-item>
                            <vxe-form-item field="viewName" title="视图名称" :span="12" :item-render="{name:'input'}"></vxe-form-item>
                            <vxe-form-item field="database" title="数据库" :span="12" :item-render="{name:'input'}"></vxe-form-item>
                            <vxe-form-item field="allowSql" title="Sql创建" :span="12" :item-render="{name:'$checkbox',props:{checkedValue:1,uncheckedValue:0}}"></vxe-form-item>
                            <vxe-form-item field="memo" title="备注" :span="24" :item-render="{name:'input'}"></vxe-form-item>
                            <vxe-form-item field="sqlCode" title="SQL" v-if="form.allowSql===1" :span="24" :item-render="{name:'$textarea',resize:true,props:{ autosize:{minRows: 6, maxRows: 10}}}"></vxe-form-item>
                            <vxe-form-item v-if="form.allowSql===0" :span="24" :item-render="{}">
                                <template #default="{ data }">
                                    <el-tabs type="border-card">
                                        <el-tab-pane label="1.选择数据表">用户管理</el-tab-pane>
                                        <el-tab-pane label="2.筛选条件">配置管理</el-tab-pane>
                                        <el-tab-pane label="3.视图字段">角色管理</el-tab-pane>
                                        <el-tab-pane label="4.视图脚本">定时任务补偿</el-tab-pane>
                                    </el-tabs>
                                </template>
                            </vxe-form-item>
                            <vxe-form-item align="center" :span="24" :item-render="{}">
                                <template #default>
                                    <el-button size="mini" @click="testSql">测试预览</el-button>
                                    <el-button size="mini" @click="buildfield">生成字段</el-button>
                                    <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
                                    <el-button size="mini" @click="cancel">取 消</el-button>
                                </template>


                            </vxe-form-item>
                        </vxe-form>
                        <vxe-table
                                show-overflow
                                ref="fields"
                                size="mini"
                                height="300"
                                :tree-config="{}"
                                :data="FieldData"
                        >
                            <vxe-column type="seq"></vxe-column>
                            <vxe-column field="fieldName" title="字段名"></vxe-column>
                            <vxe-column field="fieldExpr" title="别名"></vxe-column>
                            <vxe-column field="baseDataType" title="类型"></vxe-column>
                        </vxe-table>
                    </div>
                </el-main>
            </el-container>
        </el-container>



        <el-dialog :title="title" v-model="open" width="800px" append-to-body :close-on-click-modal="false">

          </el-dialog>
        <el-dialog title="SQL测试数据" v-model="testopen" width="800px" append-to-body :close-on-click-modal="false">
            <vxe-table border ref="testsql" :data="testData" height="530" size="mini">
              <vxe-column type="checkbox" width="40"></vxe-column>
              <vxe-column resizable show-overflow v-for="it in Fields" :field="it.field" :title="it.title"></vxe-column>
            </vxe-table>
        </el-dialog>
    </div>
</template>

<script>
import {ref,reactive,toRefs,onBeforeMount} from "vue-demi"
import XEUtils, {assign} from 'xe-utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import {listViews} from "/@/api/linkoo/views";
import TemplateEdit from "/@/views/linkoo/components/templateEdit.vue";
export default {
    components: {TemplateEdit},
    setup(){
        let loading = ref(false)
        let lkViewList = ref([])
        let total=ref(0)
        let title=ref('')
        let single = ref(true)
        let multiple=ref(true)
        let listGrid=ref()
        let open=ref(false)
        let testopen=ref(false)
        let fields = ref(null)
        // 查询参数
      let state=reactive({
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                viewID: undefined,
                viewDispName: undefined,
                viewName: undefined,
                filterExpr: undefined,
                iSUnique: undefined,
                allowSql: undefined,
                sqlCode: undefined,
                memo: undefined,
                categoryID: undefined,
                createUser: undefined,
                createTime: undefined,
                lastModUser: undefined,
                lastModTime: undefined,
                otherDesigner: undefined
            },
            lkViewList: [],
            ids: [],
            form: {},
            FieldData: [],
            Fields: [],
            testData:[]
      }) 
        onBeforeMount(()=>{
            getList()
        })
        const getList=()=>{
            listViews().then(response=>{
                ElMessage({
                    type: 'success',
                    message: '页数确定',
                })
                state.lkViewList = response.data.list
                total.value = response.data.total
            })

        }
        const handleSelectionChange=({row})=>{
            state.form=assign({},row)
            // console.log(row)
            // state.ids = selection.map(item => item.viewID)
            // single.value = selection.length != 1
            // multiple.value = !selection.length
        }
        const handleUpdate=(row)=>{
            reset()
            const viewID = row.viewID || state.ids
            console.log(viewID);
            ElMessage({
                    type: 'success',
                    message: '修改已经注释，id是='+viewID,
                })
            getLkView(viewID).then(response => {
                let data = response.data
                state.form = data
                open.value = true
                getFieldList()
                title.value = '修改视图'
            })
        }
        const getFieldList=()=> {

            listLkViewFields({pageNum: 1,pageSize: 100,viewID: state.form.viewID}).then(response => {
                state.FieldData = response.data.list?response.data.list:[]
                // this.total = response.data.total;
                // this.loading = false;
            })
        }
        // 表单重置
        const reset=()=> {
            state.form = {
                viewID: undefined,
                viewDispName: undefined,
                viewName: undefined,
                filterExpr: undefined,
                iSUnique: undefined,
                allowSql: undefined,
                sqlCode: undefined,
                memo: undefined,
                categoryID: undefined,
                createUser: undefined,
                createTime: undefined,
                lastModUser: undefined,
                lastModTime: undefined,
                otherDesigner: undefined
            }
            // resetForm('form')
        }
        /** 删除按钮操作 */
        const handleDelete=(row)=> {
            const viewIDs = row.viewID || state.ids
            ElMessageBox.confirm('是否确认删除视图编号为"' + viewIDs + '"的数据项?','警告',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(()=>{
                ElMessage({
                    type: 'success',
                    message: 'Delete completed',
                })
            }).catch(() => {
                
            })
            // this.$confirm('是否确认删除视图编号为"' + viewIDs + '"的数据项?', '警告', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(function() {
            //     return delLkView(viewIDs)
            // }).then(() => {
            //     this.getList()
            //     this.msgSuccess('删除成功')
            // }).catch(function() {
            // })
        }
        const handleAdd=()=>{
            reset()
            open.value = true
            title.value = '添加视图'
        }
        const handleQuery=()=>{
            state.queryParams.pageNum = 1
            getList()
        }
        const testSql=()=> {
            state.Fields = []
            testopen.value = true
            // testsql(state.form.sqlCode,state.form.viewName).then(res => {
            //     XEUtils.objectEach(res.data[0], (item, key) => {
            //     state.Fields.push({ field: key, title: key ,width:100})
            //     })
            //     state.testData = res.data
            //     testopen.value = true
            // })
        }
        const buildfield = ()=>{
            if(state.Fields.length>0){
                const ff=fields.value.getTableData().fullData
                state.Fields.forEach(row=>{
                if(XEUtils.find(ff, item => item.fieldName === row.field)){
                }else {
                    let field={
                    "viewFieldID": 0,
                    "viewID": state.form.viewID,
                    "fieldExpr": row.title,
                    "fieldName": row.title,
                    "baseDataType": 0,
                    "dispSeq": 0
                    }
                    state.FieldData.push(field)
                }
                })
                setTimeout(()=>{
                    state.form['Fields']=fields.value.getTableData().fullData.map((row, index) => {delete row['_X_ID'];return row })
                },30)
            }else{
                ElMessage({
                    type: 'error',
                    message: '测试预览成功后才能生成字段!!',
                })
            }
        }
        const submitForm =()=>{
            if (state.form.viewID != undefined) {
                open.value = false
                // updateLkView(state.form).then(response => {
                // if (response.code === 0) {
                //     msgSuccess('修改成功')
                //      ElMessage({type: 'success', message: '修改成功',})
                //     open.value = false
                //     getList()
                // } else {
                //     ElMessage({type: 'error', message: 'response.msg',})
                // }
                // })
            } else {
                open.value = false
                // addLkView(state.form).then(response => {
                // if (response.code === 0) {
                //     ElMessage({type: 'success', message: '新增成功',})
                //     open.value = false
                //     getList()
                // } else {
                //     ElMessage({type: 'error', message: 'response.msg',})
                // }
                // })
            }
        }
        const cancel =()=>{
            open.value = false
            reset()
        }
        return{
            loading,
            lkViewList,
            total,
            single,
            multiple,
            open,
            testopen,
            title,listGrid,
            fields,
            ...toRefs(state),
            handleSelectionChange,
            handleUpdate,
            reset,
            getFieldList,
            handleDelete,
            handleAdd,
            getList,
            testSql,
            buildfield,
            submitForm,
            cancel
        }
    }
}
</script>

<style scoped>
.el-header{
        padding: 0;
        height: 40px;
    }
    .el-main{
        border-radius: 5px;
        padding: 0;
    }
</style>